package edu.citadel.db;

import edu.citadel.domain.Client;
import edu.citadel.domain.Job;
import edu.citadel.domain.WorkItem;
import edu.citadel.utils.CollectionUtils;

import java.util.List;

/**
 * User: jordan
 * Date: 3/15/13
 * Time: 3:31 PM
 */
public class ClientDao extends ContactDao {

    public void save(Client client) {
        saveContact(client);
        getSqlTemplate().insert("client.save", client);
    }

    public Client getClientById(int clientId) {
        return (Client) getSqlTemplate().queryForObject("client.getClientById", clientId);
    }

    public Client getClientByContactId(int contactId) {
        return (Client) getSqlTemplate().queryForObject("client.getClientByContactId", contactId);
    }

    public List<Client> getAllClients() {
        getLogger().info("SELECTING ALL CLIENTS!");
        List<Client> clients =  CollectionUtils.makeGeneric(getSqlTemplate().queryForList("client.getAll"), Client.class);
        getLogger().info("FOUND " + clients.size() + " clients!");
        for (Client client : clients) {
            getLogger().info("FOUnd ids: " + client.getContactId() + " | " + client.getClientId());
        }
        return clients;
    }

    public void deleteClient(Client client) {
        getLogger().info("DELETING CLIENT : " + client.getFirstName() + " " + client.getLastName());

        for (Job job : client.getClientJobs()) {
            for (WorkItem item : job.getJobWorkItems()) {
                getSqlTemplate().delete("employee.deleteAssignedWorkByWorkItemId", item.getWorkItemId());
                getSqlTemplate().delete("employeeCompensation.deleteByWorkItemId", item.getWorkItemId());
                getSqlTemplate().delete("payment.deletePaymentsByWorkItemId", item.getWorkItemId());
            }
            getSqlTemplate().delete("workItem.deleteWorkItemsByJobId", job.getJobId());
        }

        getSqlTemplate().delete("job.deleteByClientId", client.getClientId());
        getSqlTemplate().delete("client.deleteByContactId", client.getContactId());
        getSqlTemplate().delete("contact.deleteByContactId", client.getContactId());
    }

}
